<template>
  <div class="page-template-main"
       :style="{ height: contentHeight }">
    <div :id="searchConditionContainerId"></div>
    <div class="page-template-header">
      <div class="page-template-top"
           v-if="title">
        <span>{{ title }}</span>
        <span>({{ tableConfig.pagination.total }})</span>
      </div>
      <template v-if="toolButtonList.length > 0">
        <CommonCounter v-show="tableConfig.selectedRows.length > 0"
                       :total="tableConfig.pagination.total"
                       :currentSelected="tableConfig.selectedRows.length"
                       @cancelSelected="handleCancelSelected" />
        <div style="flex: 1; overflow: hidden">
          <CommonToolbar :allToolBtns="toolButtonList"
                         @buttonClick="$emit('onToolClick', $event, params, resetTableDataOfToolClick)"
                         @checkOnchange="handleToolCheckboxChange">
          </CommonToolbar>
        </div>
      </template>
      <div class="search-part">
        <a-input-search :placeholder="$i18n('collaboration.new.template.search.keyWords')"
                        style="width: 272px"
                        :allowClear="true"
                        @change="onInputSearchValueChange"
                        @search="handleSearch" />
        <div style="margin-left: 12px; padding-right: 16px; display: flex">
          <SearchCondition :containerParentId="searchConditionContainerId"
                           :conditions="searchConditions"
                           @valueChange="handleSearchConditionChange"
                           @expandChange="onExpandChange">
          </SearchCondition>
        </div>
      </div>
    </div>
    <div class="page-template-content">
      <div class="table-parent">
        <AVirtuallyTable ref="avirtuallyTable"
                         size="small"
                         :isAbsolute="true"
                         :row-selection="isShowTableCheckbox ? tableConfig.rowSelection : null"
                         :rowKey="tableConfig.rowKey"
                         :pagination="true"
                         :openVirtuallyModel="true"
                         :paginationOption="tableConfig.pagination"
                         :columns="tableConfig.columns"
                         :dataSource="tableConfig.tableDataList"
                         :titleRightMenus="tableConfig.titleRightMenus"
                         @paginationShowSizeChange="paginationShowSizeChange"
                         @paginationChange="handleTableChange"
                         @rowClick="$emit('onRowClick', $event)">
          <template v-for="(slotIndex, name) in $scopedSlots"
                    :slot="name"
                    slot-scope="{text, record, index}">
            <slot :name="name"
                  v-bind="{ text, record, index, resetTableData }"></slot>
          </template>
        </AVirtuallyTable>
      </div>
    </div>
  </div>
</template>

<script>
  import CommonToolbar from '@/components/common-toolbar/index';
  import CommonCounter from '../../components/common-counter/index';
  import SearchCondition from '@/components/search-condition/index.vue';
  import AVirtuallyTable from '@/ant-virtually-table/table.vue';
  import { getFinishList, getMetaData } from '../../entries/finish-list/api';
  import { loadComponentsThemeDefaultCSS } from '@/utils';
  import { formatRequestDataToJSON, loadExtendResource } from '@/utils/api';

  let loadingInstance = {
    init() { },
    close() { },
    show() { },
    empty:true,
  };

  export default {
    name: 'PageTemplate',
    components: {
      CommonToolbar,
      CommonCounter,
      SearchCondition,
      AVirtuallyTable
    },
    props: {
      rowKey: {
        type: String,
        default: 'id'
      },
      title: {
        type: String,
        default: undefined
      },
      isShowTableCheckbox: {
        type: Boolean,
        default: true
      },
      tableRequest: {
        type: Object,
        default: function () {
          return {
            url: undefined,
            managerMethod: '',
            otherArgs: {}
          };
        }
      },
      metaDataRequestParams: Object,
      toolButtonList: {
        type: Array,
        default: function () {
          return [];
        }
      },
      tableSlotNames: {
        type: Array,
        default: function () {
          return [];
        }
      },
      multiDateConditionFormatType: {
        type: 0,
        default: 0 //0:日期组用#连接，1：日期组用begin/end生成新的查询key
      },
      contentHeight: {
        type: String,
        default: 'calc(100vh - 40px)'
      }
    },
    data() {
      return {
        tableConfig: {
          rowKey: this.rowKey,
          pagination: {
            page: 1,
            total: 0
          },
          rowSelection: {
            columnWidth: 60,
            selectedRowKeys: [],
            onChange: this.handleSelectChange
          },
          tableDataList: [],
          columns: [],
          titleRightMenus: {
            asc: true,
            desc: true,
            freeze: true,
            fieldset: true
          },
          selectedRows: []
        },
        searchConditionContainerId: 'search-condition-container-parent',
        searchConditions: [],
        searchText: '',
        searchConditionsValue: {},
        toolCheckboxListValue: {},
        metaData: {}
      };
    },
    computed: {
      params() {
        return {
          selectedRows: this.tableConfig.selectedRows,
          metaData: this.metaData,
          searchConditionsValue: {
            ...this.tableRequest.otherArgs,
            ...this.toolCheckboxListValue,
            ...this.searchConditionsValue,
            isGroupBy: this.metaData.globalParam ? this.metaData.globalParam.isGroupBy : undefined,
            subject: this.searchText
          }
        };
      },
      multiDateConditionList() {
        return this.searchConditions
          .filter(({ type }) => type === 'DATE_MULTI')
          .map(({ key }) => key);
      },
      multiSelectList() {
        return this.searchConditions
          .filter(({ type }) => type === 'SELECT_MULTI')
          .map(({ key }) => key);
      }
    },
    created() {
      this.init();
      loadComponentsThemeDefaultCSS(window._ctxPath + window._ctpSkinUrl);
    },
    methods: {
      formatSearchConditions(searchConditionsValue) {
        Object.keys(searchConditionsValue).forEach((key) => {
          if (this.multiDateConditionList.includes(key)) {
            const { startDate, endDate } = searchConditionsValue[key];
            if (this.multiDateConditionFormatType === 0) {
              searchConditionsValue[key] = startDate + '#' + endDate;
            } else if (this.multiDateConditionFormatType === 1) {
              searchConditionsValue['begin_' + key] = startDate;
              searchConditionsValue['end_' + key] = endDate;
            }
          }
          if (this.multiSelectList.includes(key)) {
            searchConditionsValue[key] = searchConditionsValue[key].join(',');
          }
        });
        return searchConditionsValue;
      },
      init() {
        //this.initTableData();
        this.initMetaData();
      },
      showLoading() {
        if (loadingInstance.empty){
          //动态引入防止新建页面错误逻辑发送后出现转圈
          import(/* webpackChunkName: "chunk-loading" */ '@/utils/loading.js')
              .then(md=>loadingInstance=md.loadingInstance)
          return;
        }
        loadingInstance.show();
      },
      initTableData() {
        this.showLoading()
        const params = `managerMethod=${
          this.tableRequest.managerMethod
        }&arguments=${formatRequestDataToJSON([
          { page: this.tableConfig.pagination.page, size: this.tableConfig.pagination.pageSize },
          this.params.searchConditionsValue
        ])}`;

        if (this.cancelToken && this.cancelToken.cancel) {
          this.cancelToken.cancel();
          this.cancelToken = null;
        }
        this.cancelToken = axios.CancelToken.source();

        getFinishList(this.tableRequest.url, params, this.cancelToken).then(
          ({ data: { data: tableData, total } }) => {
            this.tableConfig.tableDataList = tableData;
            this.tableConfig.pagination.total = total;
            loadingInstance.close();
          }
        );
      },
      initMetaData() {
        getMetaData(this.metaDataRequestParams).then((res) => {
          const {
            data: {
              data: { searchConditions, tableColumns }
            }
          } = res;
          this.metaData = res.data.data;
          this.params.searchConditionsValue.isGroupBy = this.metaData.globalParam
            ? this.metaData.globalParam.isGroupBy
            : undefined;
          this.searchConditions = searchConditions.filter((item) => item.key !== 'subject');
          loadExtendResource(this.metaData.extra?.extendResources);
          this.tableConfig.columns = tableColumns
            .filter((item) => item.title !== 'id')
            .map((item) => {
              let result = {
                key: item.key,
                dataIndex: item.key,
                title: item.title,
                width: item.width,
                minWidth: item.minWidth,
                ellipsis: true,
                dropdownMenus: {
                  fieldset: true,
                  asc: item.sortable,
                  desc: item.sortable
                },
                customCell: (column) => {
                  const fontBlod = this.isBlod(column) ? 'bold' : '';
                  return {
                    style: {
                      // 'font-weight': fontBlod,
                      // 'font-size': '12px',
                      padding: '0 8px',
                      height: '38px',
                      cursor: 'pointer'
                    }
                  };
                }
              };
              if (this.tableSlotNames.includes(item.key)) {
                result.scopedSlots = { customRender: item.key };
              }
              return result;
            });
          this.$emit('onMetaDataChange', res.data.data);
          this.initTableData();
        });
      },
      resetTableData() {
        this.resetTableSelectValue();
        this.tableConfig.pagination.page = 1;
        this.initTableData();
      },
      resetTableDataOfToolClick(pagination, args) {
        this.resetTableData();
      },
      resetTableSelectValue() {
        this.isShowTableCheckbox &&
          this.$refs.avirtuallyTable &&
          this.$refs.avirtuallyTable.cleanSelection();
      },
      handleToolCheckboxChange({ id: buttonId, checked }) {
        this.toolCheckboxListValue[buttonId] = String(checked);
        this.resetTableData();
      },
      handleSelectChange(selectedRowKeys, selectedRows) {
        this.tableConfig.rowSelection.selectedRowKeys = selectedRowKeys;
        this.tableConfig.selectedRows = selectedRows;
      },
      onInputSearchValueChange(e) {
        this.searchText = e.target.value;
      },
      handleSearch(value) {
        this.searchText = value;
        this.resetTableData();
      },
      handleSearchConditionChange(value, formatedValue) {
        this.searchConditionsValue = this.formatSearchConditions(value);
        this.resetTableData();
      },
      handleTableChange(page, pageSize) {
        this.tableConfig.pagination.page = page;
        this.tableConfig.pagination.pageSize = pageSize;
        this.initTableData();
      },
      paginationShowSizeChange(current, size) {
        this.tableConfig.pagination.pageSize = size;
        this.resetTableData();
      },
      handleCancelSelected() {
        this.resetTableSelectValue();
      },
      onExpandChange(isExpanded) {
        this.$nextTick(() => {
          this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.resizeTable();
        });
      },
      isBlod(record) {
        const { readState, subState } = record;
        // 未读，加粗显示， 代理也要加粗
        if (readState === 0 || subState === 11) {
          return true;
        } else {
          return false;
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .page-template-main {
    position: relative;
    display: flex;
    flex-direction: column;

    .page-template-top {
      display: flex;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
      color: #333333;
      flex: 1 1 auto;
    }

    .page-template-header {
      display: flex;
      //justify-content: space-between;
      justify-content: end;
      padding: 12px 0px 12px 0px;
      height: 54px;
      box-sizing: border-box;
    }

    .search-part {
      // flex-grow: 1;
      -webkit-transform: scale(1.0001);
      flex-shrink: 0;
      display: flex;
      justify-content: flex-end;
      overflow: hidden;
      margin-left: 100px;
    }

    .page-template-content {
      position: relative;
      overflow: hidden;
      flex: 1;
      // padding: 0 10px 0 0px;
      background-color: #ffffff;

      .table-parent {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
      }
    }

    .tag-show {
      border-radius: 2px;
      border: none;
    }
  }
</style>
<style>
  .ant-tabs-bar {
    margin-bottom: 0 !important;
  }
</style>
